#include <stdio.h>
#include <stdlib.h>

#define BOOL    int
#define FALSE   0
#define TRUE    1

#include "places.h"
#include "queue.h"
 
 
/* begin: private function section */
static void place_list_append_element (PlaceListElement *element, PLACE* element_value)
{
  if (element)
    {
      place_list_append_element (element->next, element_value);
      if (!element->next)
        {
          element->next =
              (PlaceListElement *) malloc (sizeof (PlaceListElement));
          element->next->element_value = element_value;
          element->next->next = NULL;
        }
    }
}

static void place_list_free_element (PlaceListElement *element)
{
	if (element)
	{
		place_list_free_element (element->next);
		free (element);
	}
}
/* end: private function section */
 
/* begin: public function section */
void place_list_append_constant_time (PlaceList *list, PLACE* element_value)
{
  if (!list->first)
    {
      list->first =
        (PlaceListElement *) malloc (sizeof (PlaceListElement));
      list->first->next = NULL;
      list->first->element_value = element_value;
      list->last = list->first;
    }
  else
    {
      list->last->next =
        (PlaceListElement *) malloc (sizeof (PlaceListElement));
      list->last->next->element_value = element_value;
      list->last->next->next = NULL;
      list->last = list->last->next;
    }
}
 
PlaceList* place_list_create ()
{
  PlaceList *new_list;
 
  new_list = (PlaceList *) malloc (sizeof (PlaceList));
  new_list->first = NULL;
  new_list->last = NULL;
 
  return new_list;
}
 
PLACE* place_list_pop (PlaceList *list)
{
	PlaceListElement* element = list->first;
	PLACE* result = NULL;
	if (element)
	{
		result = element->element_value;
		if (element->next)
		{
			list->first = element->next;
		}
		else
		{
			list->first = NULL;
			list->last = NULL;
		}
	}
	free(element);
	return result;
}

void place_list_clear (PlaceList *list)
{
	place_list_free_element(list->first);
	list->first = NULL;	
	list->last = NULL;
}

BOOL place_list_is_empty (PlaceList* list)
{
	if (list->first)
		return FALSE;
	return TRUE;
}

PLACE* place_list_element_at (PlaceList* list, int index)
{
	PlaceListElement* element;
	element = list->first;
	int i = 0;
	while (i < index)
	{
		element = element->next;
		i++;
	}
	return element->element_value;
}
/* end: public function section */
